﻿//-----------------------------------------------------------------------
// <copyright file="EmailController.cs" company="OverrideThis">
//     Copyright (c) 2010 OverrideThis.com
// </copyright>
//-----------------------------------------------------------------------
namespace OverrideThis.ContactManager.WebSite.Controllers
{
    using System.Linq;
    using System.Web.Mvc;
    using OverrideThis.ContactManager.Domain;
    using OverrideThis.ContactManager.WebSite.Models;
    using OverrideThis.Core.Infrastucture.Mapper;
    using OverrideThis.Core.Infrastucture.Repository;

    public class EmailController : Controller
    {
        private readonly IRepository repository;
        private readonly IMapper mapper;

        public EmailController(IRepository repository, IMapper mapper)
        {
            this.repository = repository;
            this.mapper = mapper;
        }

        public ActionResult Detail(int id)
        {
            var email = this.repository.Get<Email>()
                .FirstOrDefault(e => e.Id == id);
            var model = this.mapper.Map<Email, EmailViewModel>(email);
            return this.View(model);
        }

        [HttpGet]
        public ActionResult Create(int id)
        {
            var model = new EmailViewModel();
            model.PersonId = id;
            return this.View(model);
        }

        [HttpPost]
        public ActionResult Create(EmailViewModel model)
        {
            if (ModelState.IsValid)
            {
                var email = new Email {
                    EmailAddress = model.EmailAddress,
                    Person = this.repository.Get<Person>().First(p => p.Id == model.PersonId)
                };
                this.repository.WithTransaction(r => r.SaveOrUpdate(email));
                return this.RedirectToAction("Index", "Person", new {id = model.PersonId});
            }
            return this.View(model);
        }
    }
}